var userid = "";
var ssoSystemHtml = "";
var editflag = '0';

$(document).ready(function () {
    userid = getParam("dldm");
    querySsoSystem();
    showTable();
    //鼠标点击事件
    document.onmousedown=function(event){
        var elementId = (event.target || event.srcElement).id;
        var elementClassName = (event.target || event.srcElement).className;
        if(elementId != 'btnSystemid' && elementClassName != 'dropdown-menu' && elementClassName != 'dropdown-header' && elementClassName != 'dropdown-option') {
            if ($("#dropdown-menu").css("display") == "block") {
                $("#dropdown-menu").css("display", "none");
            }
        }
    };
});

/**
 * 获取参数
 */
function getParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)
        return decodeURI(r[2]);   //对参数进行decodeURI解码
    return null;
}

/**
 * 查询所属系统
 */
function querySsoSystem() {
    $.ajax({
        type: "POST",
        dataType: "json",
        contentType: 'application/json',
        data:JSON.stringify({}),
        url: "ssoLog/querySsoSystem",
        success: function (jsonData) {
            dropDownList(jsonData);
        }
    });
}

function dropDownList(list) {
    if (list.length > 0) {
        ssoSystemHtml += '<div id="dropdown-menu" style="display: none;position: absolute;">'
        ssoSystemHtml += '<ul class="dropdown-menu" style="width:220px;max-height: 268px; overflow-y: auto; min-height: 103px;padding-top: 8px;margin-top:-20px;display: block;">'
        for (var i = 0; i < list.length; i++) {
            var item = list[i];
            if(item.yzjd != '1'){
                ssoSystemHtml += '<li class="dropdown-header"><span>' + item.mcaption + '</span></li>';
                for (var j = 0; j < list.length; j++) {
                    var yzjdItem = list[j];
                    if(yzjdItem.pcode == item.mcode){
                        ssoSystemHtml += '<li class="dropdown-option"><a id=\'' + yzjdItem.fcode + '\' class="dropdown-option" href="javascript:void(0);" onclick="ssoSystemOption(this)"><span class="dropdown-option" style="margin-left: 10px;font-size: 13px;">' + yzjdItem.mcaption + '</span></a></li>';
                    }
                }
            }
        }
        ssoSystemHtml += '</ul>'
        ssoSystemHtml += '</div>'
    }
}

/**
 * 查询
 */
function query() {
    showTable();
}

/**
 * 展示数据
 */
function showTable() {
    var searchCondition = $("#searchCondition").val();
    var data = {userid: userid,
                searchCondition: searchCondition};
    var columnList = [
        {
            field: 'systemid',
            title: '系统名称',
            align: 'left',
            halign: 'center',
            valign: 'middle',
            width: '150',
            formatter: function (value, row) {
                if(row.newFlag == '1') {
                    return '<button id="btnSystemid" class="form-control" onclick="systemidClick()"></button>' +
                        '<span id="systemid" style="display: none"></span><span id="systemid-value" class="systemid-value">请选择系统</span><span class="caret"></span>' + ssoSystemHtml;
                } else if(row.editFlag == '1') {
                    return '<button id="btnSystemid" class="form-control"></button>' +
                        '<span id="systemid" style="display: none">' + row.systemid + '</span><span id="systemid-value" class="systemid-value">' + row.mcaption + '</span>';
                } else {
                    return '<span>' + row.mcaption + '</span>';
                }
            }
        },
        {
            field: 'loginid',
            title: '系统用户编码',
            align: 'left',
            halign: 'center',
            valign: 'middle',
            width: '150',
            formatter: function (value, row) {
                if(row.newFlag == '1') {
                    return '<input id="loginid" maxlength="15" name="loginid" class="form-control"></input>';
                } else if(row.editFlag == '1') {
                    return '<input id="loginid" value="' + value + '" name="loginid" class="form-control"></input>';
                } else {
                    return '<span>' + value + '</span>';
                }
            }
        },
        {
            field: 'userid',
            title: '操作',
            align: 'center',
            halign: 'center',
            valign: 'middle',
            width: '120',
            formatter: function (value, row, index) {
                if(row.newFlag == '1' || row.editFlag == '1') {
                    return ' <button id="save" type="button" class="btn btn-primary-wn" style="height: 28px !important;padding:3px 4px;width: 45px;" onclick="save()">保存</button>' +
                        '<button id="cancel" type="button" class="btn btn-primary-wn" style="height: 28px !important;padding:3px 4px;width: 45px;" onclick="cancel()">取消</button>';
                } else {
                    return '<div>' +
                        '<a class="blue btnEdit" href="#" onclick="update(\'' + index + '\')">' +
                        '<i class="btn-eidt-wn " style="font-size: 125%" title="更新"></i></a>' +
                        '<a class="red" href="#" onclick="del(\'' + index + '\')">' +
                        '<i class="btn-del-wn" style="font-size: 125%" title="删除"></i></a></div>';
                }
            }
        }];

    $("#tb1").bootstrapTable('destroy').bootstrapTable({
        url: "user/usermappinglist",
        method: "POST",
        dataType: "json",
        checkbox:true,
        singleSelect:true,
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        sortable: false,                    //是否启用排序
        height: $(document).height() - 67,
        clickToSelect: true,                //是否启用点击选中行
        columns: columnList,
        pagination: true,                   //是否显示分页（*）
        sidePagination: "server",
        //每页的记录行数（*）
        pageSize: 10,
        //可供选择的每页的行数（*）
        pageList: [10, 20],
        queryParamsType: "",
        queryParams: function queryParams(params) {
            var param = data;
            var PageBean = {
                pageNo: params.pageNumber,
                pageSize: params.pageSize,
                totalRecord: 0,
                totalPage: 0,
                result: []
                // orderColumn: 'order by t1.inputtime desc'
            }
            param.page = PageBean;
            param = JSON.stringify(param);
            return param;
        }
    });
}

function systemidClick(){
    var display = $("#dropdown-menu").css("display");
    if(display == "none") {
        $("#dropdown-menu").css("display", "block");
    } else {
        $("#dropdown-menu").css("display", "none");
    }
}

function ssoSystemOption(event){
    $("#systemid").html(event.id);
    $("#systemid-value").html(event.innerText);
    $("#systemid-value").css("color", "#595757");
    systemidClick();
}

/**
 * 新增映射关系
 * */
function add(){
    if(editflag == '1'){
        LayerWn.showAlert('请先保存数据');
        return false;
    }
    editflag = '1';
    $('#tb1').bootstrapTable('insertRow', {index: 0, row: {newFlag: "1"}});
}

/**
 * 更新映射关系
 * */
function update(index){
    if(editflag == '1'){
        LayerWn.showAlert('请先保存数据');
        return false;
    }
    editflag = '1';
    var data= $('#tb1').bootstrapTable('getData',true);
    data[index].editFlag = '1';
    $('#tb1').bootstrapTable('load',data);
}

/**
 * 保存映射关系
 * */
function save(){
    var systemid = $("#systemid").html();
    var loginid = $("#loginid").val();
    if(systemid == ''){
        LayerWn.showAlert('系统业务代码不能为空');
        return false;
    }
    if(loginid == ''){
        LayerWn.showAlert('系统用户编码不能为空');
        return false;
    }
    var data = {
        userid: userid,
        systemid: systemid,
        loginid: loginid
    }
    var formJSON = JSON.stringify(data);
    $.ajax({
        type: "POST",
        contentType: 'application/json;charset=UTF-8',
        async: false,
        dataType: "json",
        url: "user/saveUserMapping",
        data: formJSON,
        success: function (jsonData) {
            if (jsonData.code == 200) {   //查询成功
                showTable();
                editflag = '0';
            } else {
                LayerWn.showFailAlert("保存失败，" + jsonData.msg);
            }
        },
        error: function() {
            LayerWn.showFailAlert("保存失败！");
        }
    });
}

/**
 * 删除映射关系
 * */
function del(indexData) {
    LayerWn.showConfirm("确定要删除该映射关系吗？", function (index) {
        var data= $('#tb1').bootstrapTable('getData',true);
        var data = {userid: data[indexData].userid,
                    systemid: data[indexData].systemid};
        formJSON = JSON.stringify(data);
        $.ajax({
            type: "POST",
            contentType: 'application/json;charset=UTF-8',
            async: false,
            dataType: "json",
            url: "user/delUserMapping",
            data: formJSON,
            success: function (jsonData) {
                if (jsonData.code == 200) {
                    LayerWn.closeLayer(index);
                    showTable();
                    editflag = '0';
                } else {
                    LayerWn.showFailAlert("删除失败，" + jsonData.msg);
                }
            },
            error: function() {
                LayerWn.showFailAlert("删除失败！");
            }
        });
    });
}

/**
 * 取消操作
 * */
function cancel(){
    showTable();
    editflag = '0';
}
